package com.example.e_comm.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.e_comm.dto.UserDTO;
import com.example.e_comm.dto.UserPageQuery;
import com.example.e_comm.dto.UserVO;
import com.example.e_comm.entity.User;
import com.example.e_comm.service.UserService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
//import java.util.logging.Logger;

@RestController
@RequestMapping("/api/user")
@RequiredArgsConstructor
public class UserController {

    private final UserService userService;

    @PostMapping("/create")
    @ResponseStatus(HttpStatus.CREATED)
    public Long create(@Valid @RequestBody UserDTO dto) {
        return userService.createUser(dto);
    }

    @GetMapping("/{id}")
    public UserVO get(@PathVariable Long id) {
        return userService.getUser(id);
    }

    @GetMapping("/page")
    public IPage<UserVO> page(UserPageQuery query) {
        return userService.pageUser(query);
    }

    @GetMapping("/list")
    public IPage<UserVO> list() {
        return userService.pageUser(new UserPageQuery());
    }

    @DeleteMapping("/delete/{id}")
    public void delete(@PathVariable Long id) {
        userService.deleteUser(id);
    }

    // ==============================================================================================================
    // 用户注册
    @PostMapping("/register")
    public ResponseEntity<?> register(@RequestBody User user) {
        try{
            boolean result = userService.register(user);
            if ( result){
                return ResponseEntity.ok("用户注册成功");
            }else {
                return ResponseEntity.ok("用户注册失败");
            }
        } catch (IllegalArgumentException e){
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
    // 用户登录
    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestParam String username
            , @RequestParam String password) {
        try{
            String token = userService.login(username, password);
            Map<String, String> response = new HashMap<>();
            response.put("token", token);
            response.put("message", "登录成功");
            return ResponseEntity.ok(response);
        }catch (IllegalArgumentException e){
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
    // 当前用户信息
    @GetMapping("/current")
    public ResponseEntity<?> getCurrentUser(@RequestHeader("Authorization") String token) {
        //（可选）添加日志，帮助调试
        Logger logger = LoggerFactory.getLogger(UserController.class);
        logger.info("当前用户信息：" + userService.getUserByToken(token));
        try {
            String clean = token.replace("Bearer ", "");
            logger.info("当前用户信息：" + userService.getUserByToken(clean));
            User user = userService.getUserByToken(clean);
            if (user != null) {
                user.setPassword(null); //屏蔽敏感数据Password
                return ResponseEntity.ok(user);
            } else {
                logger.warn("没有找到用户Token");
                return ResponseEntity.status(401).body("没有找到用户Token,或Token已过期");
            }
        }catch(Exception e){
            logger.error("请求错误：" + e);
            return ResponseEntity.status(400).body("请求错误"+ e.getMessage());
        }
    }

    // 退出登录
    @PostMapping("/logout")
    public ResponseEntity<?> logout(@RequestHeader ("Authorization") String token) {
        try{
            boolean result = userService.logout(token.replace("Bearer ",""));//过滤token中的Bearer
            if (result){
                return ResponseEntity.ok("注销成功");
            }else {
                return ResponseEntity.ok("注销失败");
            }
        } catch (IllegalArgumentException e){
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

}